/**************************************************************************
 *
 * Copyright (C) 2007 University of California, Los Angeles.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *************************************************************************/

/**
 * 
 */
package edu.ucla.cs.typecast.event;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import java.util.Vector;

import edu.ucla.cs.typecast.bloomfilter.BloomFilter;
import edu.ucla.cs.typecast.bloomfilter.BloomFilterEncoder;
import edu.ucla.cs.typecast.net.EndPoint;
import edu.ucla.cs.typecast.net.EndPointListener;
import edu.ucla.cs.typecast.net.TransportContext;
import edu.ucla.cs.typecast.net.TypeCastDispatcher;
import edu.ucla.cs.typecast.util.TypeUtil;

/**
 *
 * @date Jul 26, 2007
 */
public class EventDispatcher implements TypeCastDispatcher {
	private EndPoint endPoint; 
	private EndPointListener endPointListener; 
	private Hashtable<Class, Vector<EventRegistrationEntry>> registration = new Hashtable<Class, Vector<EventRegistrationEntry>>(); 
	private Hashtable<Object, HashSet<Class>> listenerMap = new Hashtable<Object, HashSet<Class>>(); 
	
	public EventDispatcher(EndPoint endPoint, EndPointListener listener) { 
		this.endPoint = endPoint; 
		this.endPointListener = listener; 
		listener.setTypeCastDispatcher(this); 
	}
	
	public synchronized void addEventListener(Class[] types, EventListener listener, Object handback) { 
		try { 
			EventRegistrationEntry entry = new EventRegistrationEntry(types, listener, handback); 
			Collection<Class> allTypes = TypeUtil.getAllTypes(types); 
			for(Class type : allTypes) { 
				Vector<EventRegistrationEntry> entries = registration.get(type); 
				if (entries == null) { 
					entries = new Vector<EventRegistrationEntry>(); 
					registration.put(type, entries); 
				}
				if (!entries.contains(entry)) { 
					entries.add(entry); 
				}
			}
			HashSet<Class>  set = listenerMap.get(listener); 
			if (set == null) { 
				set = new HashSet<Class>(); 
				listenerMap.put(listener, set);
			}
			set.addAll(allTypes); 		
			if (listenerMap.size() == 1) { 
				endPointListener.activate(endPoint); 
			}
			endPointListener.update(endPoint, getLBF()); 
		} catch(Throwable t) { 
			t.printStackTrace(); 
			throw new RuntimeException(t); 
		}
	}

	public synchronized void removeEventListener(EventListener listener){ 
		try { 
			HashSet<Class> types = listenerMap.get(listener); 
			if (types != null) { 
				for(Class type : types) { 
					Vector<EventRegistrationEntry> entry = registration.get(type); 
					if (entry != null) { 
						entry.remove(listener); 
					}
				}
			}
			listenerMap.remove(listener); 
			endPointListener.update(endPoint, getLBF()); 
			if (registration.isEmpty()) { 
				endPointListener.deactivate(endPoint); 
			}
		} catch(Throwable t) { 
			t.printStackTrace(); 
			throw new RuntimeException(t); 
		}
	}
	
	public void dispatch(TransportContext transportContext, InputStream inputStream) throws IOException { 
		EventUnmarshaller unmarshaller = new EventUnmarshaller(); 
		TypedEvent event = unmarshaller.unmarshall(inputStream); 
		Collection<Class> eventTypes = TypeUtil.getAllTypes(event.getTypes()); 
		HashSet<EventListener> notifiedListeners = new HashSet<EventListener>(); 
		for(Class type: eventTypes) { 
			Vector<EventRegistrationEntry> entries = registration.get(type); 
			if (entries != null) { 
				Vector<EventRegistrationEntry> v = (Vector<EventRegistrationEntry>)entries.clone(); 
				for(EventRegistrationEntry entry : v) { 
					if (entry.match(eventTypes)) { 
						try { 
							if (!notifiedListeners.contains(entry.getEventListener())) { 
								notifiedListeners.add(entry.getEventListener()); 
								entry.getEventListener().notify(event.getTypes(), event.getEvent(), entry.getHandback());
							}
						} catch(Throwable t) { 
							t.printStackTrace(); 
						}
					}
				}
			}
		}
	}

	private BloomFilter getLBF() { 
		return BloomFilterEncoder.encode(registration.keySet()); 
	}
}
